(function (doc) {
  function Seat(options) {
    this.oSeat = doc.getElementsByClassName(options.el)[0];
    this.oInput = this.oSeat.getElementsByClassName("J_input")[0];
    this.oBtn = this.oSeat.getElementsByClassName("J_btn")[0];
    this.oPerson = this.oSeat.getElementsByClassName("person")[0];
    this.tableArr = [];
    this.chooseSeat = {};
    this.chooseName = [];
    this.seatNum = options.seatNum;
    this.allNum = options.allNum;
    this.oneNum = options.oneNum;
    this.seatPersonNum = options.seatPersonNum;
    this.init();
  }
  Seat.prototype.init = function () {
    this.oBtn.addEventListener("click", this.onBtnClick.bind(this), false);
  };
  Seat.prototype.onBtnClick = function (alternative) {
    if (this.isAllFull()) {
      console.log(this.chooseSeat);
      alert("已经满员");
      return;
    }
    const name = this.oInput.value || alternative;
    if (this.isChoosed(name)) {
      alert(`${name}，您已经完成！`);
      return;
    }
    let seatNum = this.getSeat();
    this.chooseName.push(name);
    this.tableArr.push({ name: name, seat: seatNum });
    this.domRender();
  };
  Seat.prototype.getSeat = function () {
    let num = Infinity;
    do {
      num = Math.floor(Math.random() * 10 + 1);
    } while (num > this.seatNum || this.chooseSeat[num] >= this.oneNum);
    !this.chooseSeat[num]
      ? (this.chooseSeat[num] = 1)
      : (this.chooseSeat[num] += 1);
    return num;
  };
  Seat.prototype.isChoosed = function (name) {
    if (~this.chooseName.indexOf(name)) {
      return true;
    }
    return false;
  };
  Seat.prototype.domRender = function () {
    this.oPerson.innerHTML = "";
    for (let elem of this.tableArr) {
      const oTr = document.createElement("tr");
      const oTdName = document.createElement("td");
      const oTdSeat = document.createElement("td");
      oTdName.innerHTML = elem.name;
      oTdSeat.innerHTML = elem.seat;
      oTr.appendChild(oTdName);
      oTr.appendChild(oTdSeat);
      this.oPerson.appendChild(oTr);
    }
  };
  Seat.prototype.isAllFull = function () {
    return this.chooseName.length === this.allNum;
  };
  window.$Seat = Seat;
})(document);
